#!/bin/python
# -*- coding: utf-8 -*-

import os
import sys

from yaml import load
from path import path
import gdata

class EricClient(object):    
    import gdata.docs.data
    import gdata.docs.client
    def __init__(self):
        self.client = gdata.docs.client.DocsClient(source='EricClient-v1')
        self.client.ssl = True  # Force all API requests through HTTPS
        self.client.http_client.debug = False
        # repalce the following two lines with your own password
        import keyring   #  kc = OSXKeychain()
        password = keyring.get_password("EricClient-v1", "xu.mathena@gmail.com")
        # replace the above two lines with your own password 
        self.client.ClientLogin('xu.mathena@gmail.com', password, self.client.source);
    
    
    def upload(self, name, f):
        print "[INFO] Upload " + f + " to GDoc as " + name
        u ='/feeds/default/private/full?title=' + name+ '&title-exact=true&max-results=5'
        feed = self.client.GetDocList(uri = u)
        target = feed.entry[0]
        ms = gdata.data.MediaSource(file_path=f, content_type='text/html')
        updated_entry = self.client.Update(target, media_source=ms)
    

class BookTasks(object):
    def __init__(self):
        self.source = path("Contents")
        self.target = path("html")
        self.index  = self.read_index("index.yaml")
        self.client = None
    
    def read_index(self, fn):
        with open(fn, "r") as f:
            m = load(f)
        return m
        
    def drill(self, segment):
        return segment.keys()[0], segment[segment.keys()[0]]

    def convert(self, fn, extension):
        f = path(fn)
        source = self.source / f
        header = source.lines(encoding = "utf-8")[0][3:-1]
        (basename, ext) = f.splitext()
        target = path(extension) / basename + "." + extension
        print "[INFO] Convert '" + header +"'"
        os.system( "rst2html.py " + source + " " + target )
        return (header, target)
        
    def walk(self, action):
        for part in self.index['Contents']:
            part_name, content = self.drill(part)
            for chapter in content:
                chapter_name, articles = self.drill(chapter)
                if type(articles) == type(""):
                    action(articles)
                else:
                    for article in articles:
                        article_name, rst_file = self.drill(article)
                        action(rst_file)

    def upload(self, f):
        if not self.client:
            self.client = EricClient()
        (title, html) = self.convert(f, 'html')
        self.client.upload(title, html)

if __name__ == '__main__':
    bt = BookTasks()
    if sys.argv[1] == "html":
        print "Generate HTML"
        bt.walk(lambda x: bt.convert(x, "html"))
    elif sys.argv[1] == "upload":
        print "Upload files"
        if len(sys.argv) <= 2:
            bt.walk(lambda x: bt.upload(x))
        else:
            rstfile = sys.argv[2]
            if not rstfile.endswith(".rst"):
                rstfile += ".rst"
            # title, html = bt.convert(rstfile, "html")
            bt.upload( rstfile)
        
